/* eslint-disable react/require-default-props */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { TreeSelect, Spin } from 'antd';
import { everyRequire } from './utils';

const getTreeData = (data, fieldsName) =>
    data.map(item => ({
        ...item,
        value: item[fieldsName.value],
        title: item[fieldsName.title],
        key: item[fieldsName.value],
        children: item.children ? getTreeData(item.children, fieldsName) : item.children
    }));
/**
 *自定义表单控件TreeeSlect
 */
const TreeSelectForm = React.forwardRef(({ onChange, value, getData, params, ...rest }, ref) => {
    const { style, Props, fieldsName, requireParam, defaultExpand } = rest;
    const [Tree, setTree] = useState([]);
    const [loading, setLoading] = useState(false);
    const fetchTree = async () => {
        if (!everyRequire(params, requireParam)) {
            return;
        }
        setLoading(true);
        const result = await getData(params);
        setLoading(false);
        setTree(result);
    };
    useEffect(() => {
        fetchTree();
    }, JSON.stringify(params));
    return (
        <div ref={ref}>
            <Spin spinning={loading}>
                <TreeSelect
                    showSearch
                    treeDefaultExpandAll={!(defaultExpand && defaultExpand === 'department')}
                    treeNodeFilterProp="title"
                    style={{ ...style }}
                    value={value}
                    allowClear
                    treeData={getTreeData(Tree, fieldsName)}
                    onChange={onChange}
                    {...Props}
                />
            </Spin>
        </div>
    );
});

TreeSelectForm.propTypes = {
    onChange: PropTypes.func,
    /**
     * 自定义treeNode字段
     */
    fieldsName: PropTypes.object,
    /**
     * request 请求参数
     */
    params: PropTypes.object,
    /**
     * 获取数据方法
     */
    getData: PropTypes.func,
    /**
     * 覆盖TreeSelect Props
     */
    Props: PropTypes.object,
    /**
     * defaultExpand用来判断部门的时候不默认展开
     */
    defaultExpand: PropTypes.string
};

TreeSelectForm.defaultProps = {
    onChange: () => {}
};

export default TreeSelectForm;
